package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.qf.service.QueryService;
import com.qf.util.ConnectionUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.util.Map;

/*
杨威
2022/1/18
17:17
哈哈哈
*/
public class QueryServiceImpl implements QueryService {
	//什么情况 推送成功了吗
	//hello world2
	//123
    public String baseSearch(String index, QueryBuilder queryBuilder) throws Exception {
        RestHighLevelClient client = ConnectionUtil.getClient();
        SearchRequest searchRequest = new SearchRequest(index);//查询指定的库
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //通过builder来构建我们的查询条件
        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);//设置一个搜索的条件
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String s = objectMapper.writeValueAsString(response);
        return s;
    }
    public SearchResponse baseSearch2(String index, QueryBuilder queryBuilder) throws Exception {
        RestHighLevelClient client = ConnectionUtil.getClient();
        SearchRequest searchRequest = new SearchRequest(index);//查询指定的库
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //通过builder来构建我们的查询条件
        searchSourceBuilder.query(queryBuilder);
        searchRequest.source(searchSourceBuilder);//设置一个搜索的条件
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        return response;
    }
    @Override
    public void termQuery(String index, String filed, String value) throws Exception {
        String s=baseSearch(index, QueryBuilders.termQuery(filed, value));
        System.out.println("searchResponse = " + s);
    }

    @Override
    public void termsQuery(String index, String filed, String... value) throws Exception {
        String s = baseSearch(index, QueryBuilders.termsQuery(filed, value));
        System.out.println("s = " + s);
    }

    @Override
    public void matchAll(String index) throws Exception {
        String s = baseSearch(index, QueryBuilders.matchAllQuery());
        System.out.println("s = " + s);
    }

    @Override
    public void match(String index, String field, String value) throws Exception {
        String s = baseSearch(index, QueryBuilders.matchQuery(field, value));
        System.out.println("s = " + s);
    }

    @Override
    public void boolMatch(String index, String field, String value, Operator operator) throws Exception {

    }

    @Override
    public void multiMacth(String index, String value, String... fields) throws Exception {
        String s = baseSearch(index, QueryBuilders.multiMatchQuery(value, fields));
        System.out.println("s = " + s);
    }

    @Override
    public void idQuery(String index, String id) throws Exception {
        String s = baseSearch(index, QueryBuilders.idsQuery().addIds(id));
        System.out.println("s = " + s);
    }

    @Override
    public void idsQuery(String index, String... ids) throws Exception {
        String s = baseSearch(index, QueryBuilders.idsQuery().addIds(ids));
        System.out.println("s = " + s);
    }

    @Override
    public void prefixQuery(String index, String field, String prefix) throws Exception {
        String s = baseSearch(index, QueryBuilders.prefixQuery(field, prefix));
        System.out.println("s = " + s);
    }

    @Override
    public void fuzzyQuery(String index, String field, String value) throws Exception {
        String s = baseSearch(index, QueryBuilders.fuzzyQuery(field, value));
        System.out.println("s = " + s);
    }

    @Override
    public void wildcardQuery(String index, String field, String value) throws Exception {
        String s = baseSearch(index, QueryBuilders.wildcardQuery(field, value));
        System.out.println("s = " + s);
    }

    @Override
    public void rangeQuery(String index, String field, long gte, long lte) throws Exception {
        String s = baseSearch(index, QueryBuilders.rangeQuery(field).gte(gte).lte(lte));
        System.out.println("s = " + s);
    }

    @Override
    public void regQuery(String index, String field, String reg) throws Exception {
        String s = baseSearch(index, QueryBuilders.regexpQuery(field, reg));
        System.out.println("s = " + s);
    }

    @Override
    public String createScrollQuery(String index, QueryBuilder queryBuilder, int size) throws Exception {
        return null;
    }

    @Override
    public void srollQuery(String scrollId) throws Exception {

    }

    @Override
    public void clearScroll(String index, String scrollId) throws Exception {

    }

    @Override
    public void deleteByQuery(String index, QueryBuilder queryBuilder) throws Exception {

    }

    @Override
    public void boostQuery(String index, QueryBuilder queryBuilder, QueryBuilder boostBuilder, float boost) throws Exception {

    }

    @Override
    public void highLight(String index, QueryBuilder queryBuilder, HighlightBuilder highlightBuilder) throws Exception {
        RestHighLevelClient client = ConnectionUtil.getClient();
        SearchRequest searchRequest = new SearchRequest(index);//查询指定的库
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(queryBuilder);//设置查询的条件
        searchSourceBuilder.highlighter(highlightBuilder);//设置高亮的条件
        searchRequest.source(searchSourceBuilder);//设置一个搜索的条件
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        //先获取原始数据
        SearchHit[] hits = response.getHits().getHits();//获取到所有查询到的数据
        for (SearchHit hit : hits) {//办理获取每一条数据
            String id = hit.getId();//获取到主键
            Map<String, Object> hitSourceAsMap = hit.getSourceAsMap();//以map的方式接受原始数据, 如果是字符串的方式就是获取到json
//            String json = hit.getSourceAsString();//返回json格式的数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            highlightFields.forEach((fieldName,highlightField)->{
                if (highlightField != null) {//但是不是一定有高亮的,所以要判断一下
                    Text[] fragments = highlightField.getFragments();//获取到当前的高亮的片段
                    if (fragments != null && fragments.length > 0) {
                        Text fragment = fragments[0];//获取到真正的高亮的内容
                        //替换
                        hitSourceAsMap.put(fieldName, fragment.toString());//将高亮的数据替换掉原始map中的数据
                    }
                }
            });
            System.out.println(hitSourceAsMap);
        }
    }

    @Override
    public void highLight2(String index, String field, String value) throws Exception {
        SearchResponse searchResponse = baseSearch2(index, QueryBuilders.matchQuery(field, value));
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {//办理获取每一条数据
            String id = hit.getId();//获取到主键
            Map<String, Object> hitSourceAsMap = hit.getSourceAsMap();//以map的方式接受原始数据, 如果是字符串的方式就是获取到json
//            String json = hit.getSourceAsString();//返回json格式的数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            highlightFields.forEach((fieldName,highlightField)->{
                if (highlightField != null) {//但是不是一定有高亮的,所以要判断一下
                    Text[] fragments = highlightField.getFragments();//获取到当前的高亮的片段
                    if (fragments != null && fragments.length > 0) {
                        Text fragment = fragments[0];//获取到真正的高亮的内容
                        //替换
                        hitSourceAsMap.put(fieldName, fragment.toString());//将高亮的数据替换掉原始map中的数据
                    }
                }
            });
            System.out.println(hitSourceAsMap);
        }
    }

    @Override
    public void cardinalityAgg(String index, String field) throws Exception {

    }

    @Override
    public void rangeAgg(String index, AggregationBuilder aggregationBuilder) throws Exception {

    }

    @Override
    public void dateRangeAgg(String index, AggregationBuilder aggregationBuilder) throws Exception {

    }

    @Override
    public void ipRangeAgg(String index, AggregationBuilder aggregationBuilder) throws Exception {

    }

    @Override
    public void extendedStats(String index, String field) throws Exception {

    }
}
